$m(function(params){
	var body = $("body");
	if(this.element) {
		body = this.element.parent();
	}
	function MineController(){
		var mine = this,
		panel = $("#tempo-mine-container"),
		mvPanel = $("#tempo-mine-model-view-container"),
		board = $("#tempo-mine-board"),
		mimeMainBar = $('#tempo-scene-btnsbar'),
		mineEditBar = $('#tempo-scene-controlgroup');
		apiDesigner = window.apiDesigner == undefined ? false : window.apiDesigner;
		
		if(window.location.href.indexOf("isFlowView")!=-1){
			window.isFlowView=true
		}
		this.init = function(){
			renderBody();
			renderPanel();
			renderModelAndView();
			renderToolBar();
			loadAnalyseTheme();
			//initMainMenu();
			bindEvent();
			listenonUnload();
			updateButtunBar();
			var maxInactiveInterval = __maxInactiveInterval * 500;
			setInterval(function(){
				activeSession();
			}, maxInactiveInterval)
			if(window.apiDesigner) {
				$('#tempo-system-toobar').remove();
				$('#tempo-shortcut').remove();
			}
			//处理360兼容模式下浏览器页签上显示不正确的问题
			if(TempoUtils.isIE()){
				setTimeout(function () {
					$("title").text(document.title)
				},1000)
			}

		}
		var activeSession = function(){
			$.ajax({
				url : contextPath + '/api/ai/mine/activeSession',
				type : 'post',
				dataType : 'json',
				success : function(result) {
					if(result){
						console.log("session续期成功");
					}
				},
				error: function(){
					console.error("接收不到服务器响应，请询问管理员");
				}
			});
		}
		
		var updateNavigation = function(project, analyse) {
			$('<div>').navigation({
				data:[{
					id : "1",
					title : TempoUtils.locale("mine.projectCenter"),
					type : "text",
					data :　null,
					click : function(data){
						try {
							var thisUrl = contextPath + "/" + "project.jsp";
							thisUrl = TempoUtils.addHideIconParam(thisUrl);
							window.location.href = thisUrl;
						} catch (e) {
							// TODO: handle exception
						}
						return false;
					}
				},{
					id : project.ID,
					title : project.NAME,
					type : "text",
					data :　project,
					click : function(data){
						try{
							var thisUrl = contextPath + "/" + "projectView.jsp?project=" + data.id + "#mining";
							thisUrl = TempoUtils.addHideIconParam(thisUrl);
							window.location.href = thisUrl;
						} catch (e) {
							// TODO: handle exception
						}
						return false;
					}
				}, {
					id: analyse.id,
					title: analyse.name,
					type :　"select",
					option : {
						listUrl : contextPath + '/resource/queryResource',
						type : "mining",
						pid : window[constant.APP_ID],
						newName: TempoUtils.locale("mine.newwajue"),
						notShow:TempoAuthorityUtils.isDesignerLimited(),
						itemClick:function(data){
							var id = data.ID || data.id;
							var thisUrl = contextPath
							+ "/api/ai/mine/index?subjectId=" + id
							+ "&projectId=" +  window[constant.APP_ID];
							thisUrl = TempoUtils.addHideIconParam(thisUrl);
							window.location.href = thisUrl;
							return false;
						},
						newClick:function(){
							$.ajax({
								url : contextPath + ('/resource/saveTempoResource'),
								type : 'post',
								data : {
									type : "mining",
									parentId : window[constant.APP_ID]
								},
								dataType : 'json',
								success : function(obj) {
									if (obj != null) {
										window.location.href = contextPath
										+ "/api/ai/mine/index?subjectId=" + obj.ID
										+ "&projectId=" +  window[constant.APP_ID];
									}
								}
							});
							return false;
						}
					}
				}],
				iconNodeType : "story"
			}).appendTo($("#moduleNav"));
		}
		
		var updateButtunBar = function() {
			var buttons = [{
				title : TempoUtils.locale("mine.jianmo"),
				type : "1"
			},{
				title : TempoUtils.locale("mine.dongcha"),
				type : "2"
			}];
			if(!window.apiDesigner) {
				buttons.push({
					title : TempoUtils.locale("mine.bushu"),
					type : "3"
				});
			}
			var buttonbar = $("<div>").buttonbar({
				data: buttons,
				click:function(data){
					if(data.type == "1"){
						Eventbus.trigger('switchToModeling.mine');
					}else if(data.type == "2"){
						Eventbus.trigger('switchToViewing.mine');
					}else if(data.type == "3"){
						Eventbus.trigger('switchToPubling.mine');
					}
				}
			}).appendTo($("#tempo-buttonbar"));
			
			if ("ai" != "ai") {
				// 添加提示
				$("<div id='tempo-helptip-minemodel' style='display:inline-block;position: relative;top:5px;'></div>").helptip({
					cookieKey:"tempominemodel",
					width:256,
					tipShow:false,
					showOperate:true,
					showMoreHelp:true,
					contentInfo:TempoUtils.locale("mine.caozuoyanshi"),
					//operatePicSrc:"/tempo/support/zh_CN/demonstration/guide/practice01/01.png",
					operateSourceSrc:contextPath+"/images/mineanalyse.gif"
				}).prependTo(buttonbar);
			}
			var buttonCenter = {
					modeling: 0,
					viewing: 1,
					publish: 2
			};
			Eventbus.one('selectButton.mine', function(type) {
				// 防止预览模式下，跳转到洞察页面
				if(buttonCenter[type] != undefined && (!window.apiPreview || "viewing" != type)) {
					buttonbar.buttonbar('selectButton', buttonCenter[type], true);
				}
			}, buttonbar);
			
		}
		
		var initMainMenu = function(){
			/**
			 * 触发页面左上角切换按钮菜单内容
			 */
			var titleMenusData = function(){
				return [{
					text:TempoUtils.locale("mine.achievementManage"),
					id:'cggl.jsp?project='+window[constant.APP_ID]
				},{
					text:TempoUtils.locale("mine.toProject"),
					id:'projectView.jsp?project='+window[constant.APP_ID]    
				},{
					text:TempoUtils.locale("mine.projectCenter"),
					id:'index.jsp'
				}]
			}
			Eventbus.trigger("setSysMenuData.main",titleMenusData());
		}
		/**
		 * 渲染整个面板
		 */
		var renderBody = function() {
			body.layout({
				scrollToBookmarkOnLoad: false,
				north : {
					resizable : false,
					spacing_open : 0,
					closable : false
				}
			});
			
			if(!window.apiPreview) {
				var html = $('html');
				$(window).resize(function(){
					var hx = 'auto', hy = 'auto';
					if($(this).width() < 1000) {
						hx = 'scroll';
					}
					if($(this).height() < 500) {
						hy = 'scroll';
					}
					html.css({
						'overflow-x': hx,
						'overflow-y': hy
					})
				}).trigger('resize');
			} else {
				body.layout().hide('north');
				body.find('#tempo-mine-title').hide();
			}
		}
		
		var renderPanel = function() {
			panel.layout({
				scrollToBookmarkOnLoad: false,
				west : {
					resizable : false,
					size : 230,
					spacing_open : 1
				},
				center:{
					onresize_end:function(){
						//调整页面大小时调整节点位置
						//board.miningboard("updateSize");
					}
				}
			})
		}
		
		var renderModelAndView = function(){
			var layout = {
					scrollToBookmarkOnLoad: false,
					south : {
						resizable : false,
						size : 32,
						spacing_open : 1,
						closable : false,
						onresize_end: function(){
							Eventbus.trigger("model&viewChanged.mine");
						}
					},
					center:{
						onresize_end:function(){
							//调整页面大小时调整节点位置
							//board.miningboard("updateSize");
						}
					}	
			}
			// 当为ai模式时，隐藏下面的页签
			/*if(window.apiDesigner) {
			 delete layout.south;
			 mvPanel.find('> div.ui-layout-south').removeClass('ui-layout-south').hide();
		}*/
			mvPanel.layout(layout);
		}
		
		var renderToolBar = function(){
			//渲染工具条
			mimeMainBar.controlgroup();
			mineEditBar.controlgroup();
			//工具条添加事件
		}
		/**
		 * 加载分析主题
		 */
		var loadAnalyseTheme = function(){
			if(!window.apiDesigner) {
				$.ajax({
					url:contextPath+"/api/ai/mine/loadAnalyseInfo",
					data:{
						analyseId:window[constant.ANALYSE_ID]
					},
					dataType:'json',
					type:'post',
					success:function(data){
						updateTitle(data);
					}
				})
			}
		}
		/**
		 * 更新页面标题
		 */
		var updateTitle = function(data){
			document.title = data.name;
			Eventbus.trigger("mine.themechange",data.name);
			$.ajax({
				url : contextPath + '/project/findProjectById',
				type : 'post',
				data : {
					id : window[constant.APP_ID]
				},
				dataType : 'json',
				success : function(project) {
					updateNavigation(project, data);
				}
			});
		}
		
		/**
		 * 当前分析表的状态
		 */
		var analyseStatus = TempoMineUtils.analyseStatus;
		
		var bindEvent = function(){
			Eventbus.bind("getAnalyseStatus", function(){
				return analyseStatus;
			});
		}
		
		/**
		 * 监听页面卸载事件
		 */
		var listenonUnload = function(){
			//监听页面的关闭离开事件，如果有未编辑的场景， 则提示
			// 解决弹出框模式在IE下双重消息提示问题
			if(!window._useTopDialog) {
				window.onbeforeunload = function(){   
					var tabNav = $('#tempo-mine-model-tabs').find('.tempo-mine-tab-cont');
					var spans = tabNav.find("span");
					for(var i=0,len=spans.length;i<len;i++){
						var ui = $(spans[i]);
						if(ui.find(".tempo-mine-tab-change").length > 0){
							var event = event||window.event;
							if(window.event){ 
								event.returnValue=TempoUtils.locale("mine.unSavePromot"); 
							}else{
								return TempoUtils.locale("mine.unSavePromot"); 
							}
						} 	
					}
				}
			}
		}
	}
	
	$(function() {
		/**
		 * 加载后初始化应用id和场景id
		 */
		// 反序列化传入的参数
		if(params.projectId) {
			window[constant.APP_ID] = params.projectId;
		}
		if(params.subjectId) {
			window[constant.ANALYSE_ID] = params.subjectId;
		}
		if(params.analyseId) {
			window[constant.ANALYSE_ID] = params.analyseId;
		}
		if(params.id) {
			window[constant.ANALYSE_ID] = params.id;
			window.analyseId = params.id;
		}
		if(window.analyseId) {
			window[constant.ANALYSE_ID] = analyseId;
		}
		if(params.isFlab){
			window.isFlab = params.isFlab;
		}
		var mine = new MineController();
		mine.init();
		$.error = function(m) { console.error(m);}
	})
	
});